<?php
namespace app\admin\controller;
use think\Db;
use think\Session;
use think\Request;

class User extends Admincontroller
{
	/**
	 * 加载后台用户页面
	 * @return [type] [description]
	 */
	public function index()
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();

		// 查询数据
		$user = Db::name('admin')->select();

		return $this->fetch('list',['title'=>'蒸汽男孩后台','nick'=>$name['name'],'user'=>$user]);
	}

	/**
	 * 加载编辑用户页面
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function edit($id)
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();

		$data = Db::name('admin')->find($id);
		return $this->fetch('edit',['title'=>'蒸汽男孩后台','nick'=>$name['name'],'data'=>$data]);
	}

	/**
	 * 执行更新用户逻辑
	 * @param  Request $req [description]
	 * @param  [type]  $id  [description]
	 * @return [type]       [description]
	 */
	public function update(Request $req,$id)
	{
		$data = $req->post();
		$result = Db::name('admin')->where(['id'=>$id])->update(['nick'=>$data['nick']]);

		if($result > 0) {
			$this->success('修改成功',url('admin/user/index'));
		} else {
			$this->error('修改失败,请重试');
		}
	}

	/**
	 * 加载分配身份页面
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public function sf($id)
	{
		$name = Db::name('admin')->field('name')->where('name = "'.Session::get('admin').'"')->find();

		// 获得用户的所有身份
		$have_role = Db::table('ubisoft_admin a,ubisoft_role r,ubisoft_admin_role z')->field('r.name')->where('a.id = z.aid and z.rid = r.id and a.id = "'.$id.'"')->select();

		$haves = array();

		foreach ($have_role as $k => $v) {
			$haves[] = $v['name'];
		}

		$role = Db::name('role')->select();

		return $this->fetch('sf_edit',['title'=>'蒸汽男孩后台','nick'=>$name['name'],'role'=>$role,'haves'=>$haves,'id'=>$id]);
	}

	/**
	 * 执行分配身份逻辑
	 * @param  Request $req [description]
	 * @return [type]       [description]
	 */
	public function update_sf(Request $req)
	{
		$sql = $req->post();

		if(empty($sql)){
			$this->error("必须选择一个节点！");
		}

		$rids = array();
		foreach ($sql['rid'] as $k => $v) {
			$rids[] = $v;
		}
		$aids = $sql['aid'];

		Db::name('admin_role')->where(['aid'=>$aids])->delete();

		foreach ($rids as $k => $v) {
			$admin_role['rid'] = $v;
			$admin_role['aid'] = $aids;
			$data = db('admin_role')->data($admin_role)->insert();
		}

		if($data > 0) {
			$this->success('分配成功',url('admin/user/index'));
		} else {
			$this->error('分配失败');
		}
	}
}